﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using bmapi.Models.CADModel;
using bmapi.Models.DataEntity;

namespace bmapi.Controllers
{
    public class CAD37Controller : CADFinishController
    {

        // POST: api/CAD37 
        [HttpPost, Route("cad37/Finish")]
        public string Finish(dynamic json)
        {
            WriteLog("cad37/Finish", "json:"+ json.ToString(), true);
            if (json == null)
                return ReturnError(201, "参数不能为空");
            int uid = GetCrrentIDByToken();
            PC pc = GetPC(Convert.ToInt32(json.id));
            if (pc == null)
                return ReturnError(201, "流程不存在");
            if (!CheckIsCanFinish(37, pc.pc_id))
                return ReturnError(201, "该任务已被指定，你无权处理，禁止上传");
            List<PCInfo> pcinfo = ISBind(pc);
            string res = ReturnError(201, "cad37/Finish 流程处理失败"); 
            for (int i = 0; i < pcinfo.Count; i++)
            {
                res = HandleOrder(pcinfo[i], uid);
            }
            return res;
            //return ReturnError(201, "cad37/Finish 流程处理失败");
        }
        /// <summary>
        /// 处理完成的订单数据
        /// </summary>
        /// <returns></returns>
        private string HandleOrder(PCInfo pc,int uid)
        {
            WriteDebug("HandleOrder", "流程ID:"+pc.Id);
            List<SQLCommand> cmds = new List<SQLCommand>();
            XmlDocument doc = new XmlDocument();
            //xml文件路径
            string pcPath = GetPCPath(pc.Id);
            string xmlpath = pcPath + "\\" + pc.Path + ".bom";
            doc.Load(xmlpath);
            WriteDebug("HandleOrder", "bom文件路径:" + xmlpath);
            int minlsh = 0;
            //获取LSH节点列表   
            XmlNodeList lshparam = doc.GetElementsByTagName("param");
            if (lshparam.Count > 0)
                cmds.AddRange(UpdateLSH(lshparam, pc.Id, ref minlsh));
            else
            {
                WriteDebug("cad37/Finish", "不存在LSH节点列表");
                return ReturnError(201, "不存在LSH节点列表");
            }
            //修改Order_tb  获取面料用量  由于xml文件中是bomlist集合  故按有多个bom来处理  增加代码的扩展性
            XmlNodeList boms = doc.GetElementsByTagName("bom");
            if (boms.Count > 0)
                cmds.AddRange(UpdateOrder(boms, pc.Id, minlsh));
            else
                WriteDebug("cad37/Finish", "不存在bomlist集合");
            //获取bed节点列表 
            XmlNodeList bedList = doc.GetElementsByTagName("bed");
            if (bedList.Count > 0)
                cmds.AddRange(AddBed(uid, pc, bedList));
            else
            {
                WriteDebug("cad37/Finish", "不存在bed节点列表");
                return ReturnError(201, "不存在bed节点列表");
            }
            try
            {
                int rtn = SQLCommand.ExecTran(cmds);
                if (rtn == 1)
                {
                    WriteDebug("cad37/Finish", "数据更新成功，开始移动文件夹");
                    //将cut文件移动到buyiCut文件夹下 
                    string cutPath = m_buyiRoot + "\\buyiCut\\" + pc.Path;
                    string sourcePath = pcPath + "\\cut";
                    WriteDebug("cad37/Finish", "cutPath："+ cutPath);
                    //if (Directory.Exists(sourcePath))
                    MoveCut(sourcePath, cutPath, pc);
                    return ReturnError(200, "OK");
                }
                else
                {
                    WriteDebug("cad37/Finish", "数据更新失败+" + cmds.Count);
                    return ReturnError(201, "数据更新失败");
                }
            }
            catch (Exception e)
            {
                WriteDebug("cad37/Finish", "数据更新失败," + e.Message);
                return ReturnError(201, "数据更新失败");
            }
        }

        /// <summary>
        /// 获取绑定订单id  或者单个id
        /// </summary> 
        /// <param name="pc"></param>
        /// <returns></returns>
        private List<PCInfo> ISBind(PC pc)
        {
            List<PCInfo> pcid = new List<PCInfo>();
            PCInfo p = null;
            if (pc.bind_id == 0)
                pcid.Add(p=new PCInfo(pc.pc_id,pc.path,pc.PLID));
            else
            {
                WriteDebug("ISBind", "绑定订单的处理，绑定号：" + pc.bind_id);
                string sql = "select pc_id,path,PLID from PC_tb where bind_id=@bindid";
                SQLCommand sc = new SQLCommand(sql, "@bindid", pc.bind_id);
                DataTable dt = sc.ExecuteScalars();
                if (dt == null)
                    pcid.Add(p = new PCInfo(pc.pc_id, pc.path,pc.PLID));
                else
                {
                    foreach (DataRow  item in dt.Rows)
                    {
                        pcid.Add(p = new PCInfo(Convert.ToInt32(item["pc_id"]), item["path"].ToString(), Convert.ToInt32(item["PLID"])));
                    }
                }
            }
            return pcid;
        }

        /// <summary>
        /// 移动cut文件目录 
        /// </summary>  
        /// <param name="sourcePath"></param>
        /// <param name="cutPath"></param>
        private void MoveCut(string sourcePath, string cutPath,PCInfo pc)
        {
            if (!Directory.Exists(sourcePath))
                WriteDebug("MoveCut", "不存在目录," + sourcePath);
            else
            {
                if (Directory.Exists(cutPath))
                {
                    //删除文件目录   
                    Directory.Delete(cutPath, true);
                    Directory.Move(sourcePath, cutPath);                    
                }
                else
                    Directory.Move(sourcePath, cutPath);               
            }
            //37完成删除PC_tb记录改变Order_tb状态,移动文件目录
            
            string pcPath = GetPCPath(pc.Id);
            Finish37(pc, pcPath);
        }
        /// <summary>
        /// 37的完成处理 
        /// </summary>删除PC_tb记录改变Order_tb状态,移动文件目录到history
        /// <param name="pc"></param> 
        /// <param name="pcPath"></param>
        private void Finish37(PCInfo pc, string pcPath)
        {
            try
            {
                List<SQLCommand> cmds = new List<SQLCommand>();
                SQLCommand sc = null;
                //删除流程
                string sql = "delete PC_tb where pc_id=@pcid";
                sc = new SQLCommand(sql, "@pcid", pc.Id);
                cmds.Add(sc);
                //修改Order表床数以及状态  
                sc = new SQLCommand("select count(id) from Bed_tb where order_id=@orderid", "@orderid", pc.Id);
                int beds = Convert.ToInt32(sc.ExecuteScalar());
                
                sql = "update Order_tb set state=2,bed=@bed where id=@orderid";
                sc = new SQLCommand(sql);
                sc.Add("@bed", beds);
                sc.Add("@orderid", pc.Id);
                cmds.Add(sc);
                WriteDebug("Finish37", "床数:" + beds + "流程Id:" + pc.Id);
                //修改bed状态    
                sc = new SQLCommand("update Bed_tb set state=1 where order_id=@orderid", "@orderid", pc.Id);
                cmds.Add(sc);
                int rtn = SQLCommand.ExecTran(cmds);
                if (rtn == 1)
                {
                    WriteDebug("Finish37", "成功删除PC以及修改order状态,开始移动文件夹");
                    sql = "select creater_time from Order_tb where id=@orderid";
                    sc = new SQLCommand(sql, "@orderid", pc.Id);

                    DateTime res = Convert.ToDateTime(sc.ExecuteScalar());
                    string hisPath = m_buyiRoot + "\\buyiHistory\\";
                    
                    hisPath += res.ToString("yyyyMM");
                    if (!Directory.Exists(hisPath))
                        Directory.CreateDirectory(hisPath);                    
                   
                    //删除文件目录
                    string orderPath = hisPath + "\\" + pc.Path;
                    if (Directory.Exists(orderPath))
                        Directory.Delete(orderPath, true);
                    WriteDebug("Finish37", "pcPath：" + pcPath+"，orderpath："+orderPath);
                    Directory.Move(pcPath, orderPath);
                    WriteDebug("Finish37", "成功");
                }
            }
            catch (Exception e)
            {
                WriteDebug("Finish37", "异常：" + e.Message);
            }

        }
        /// <summary>
        /// 成功删除PC以及修改order状态,开始移动文件夹
        /// </summary>    
        /// <param name="pc"></param>
        private void MoveFinishOrderFile(PC pc)
        {
            WriteDebug("Finish37", "成功删除PC以及修改order状态,开始移动文件夹");
            SQLCommand sc = null;
            DataTable dt = null;
            if (pc.bind_id != 0) //是绑定处理  获取所有绑定订单的id
            {
                string sqlids = "select id,name from Order_tb where bind_id=@bindid and state =2";
                sc = new SQLCommand(sqlids, "@bindid", pc.bind_id);
                dt = sc.ExecuteScalars();
                foreach (DataRow item in dt.Rows)
                {
                    int pcid = Convert.ToInt32(item["id"]);
                    Move(pcid, item["name"].ToString());
                }
            }
            else
            {
                Move(pc.pc_id,pc.path);
            }
           
            //string sql = "select creater_time from Order_tb where id=@orderid";
            //sc = new SQLCommand(sql, "@orderid", pc.pc_id);

            //DateTime res = Convert.ToDateTime(sc.ExecuteScalar());
            //string hisPath = m_buyiRoot + "\\buyiHistory\\";
            //hisPath += res.ToString("yyyyMM");

            //if (!Directory.Exists(hisPath))
            //    Directory.CreateDirectory(hisPath);
                                                                                    
            //Directory.Move(pcPath, hisPath + "\\" + pc.path);


            WriteDebug("Finish37", "成功");
        }
        private void Move(int pcid,string path)
        {
            try
            {
                string pcPath = GetPCPath(pcid);
                string sql = "select creater_time from Order_tb where id=@orderid";
                SQLCommand sc = new SQLCommand(sql, "@orderid", pcid);
                DateTime res = Convert.ToDateTime(sc.ExecuteScalar());

                string hisPath = m_buyiRoot + "\\buyiHistory\\";
                hisPath += res.ToString("yyyyMM");

                if (!Directory.Exists(hisPath))
                    Directory.CreateDirectory(hisPath);

                Directory.Move(pcPath, hisPath + "\\" + path);
            }
            catch (Exception ex)
            {
                WriteDebug("37Move", "文件移动出错:" + ex.Message);
                throw;
            }
           
        }

        /// <summary>
        /// 修改流水号  记录最大流水号  然后按照件数递减(-1)
        /// </summary> 
        /// <param name="lshparam"></param>
        /// <param name="orderid"></param>
        /// <returns></returns>
        private List<SQLCommand> UpdateLSH(XmlNodeList lshparam,int orderid,ref int minLsh)
        {
            List<SQLCommand> cmds = new List<SQLCommand>();
            //将lsh全部置为0  以防出错
            string sql = "update LSH_tb set LSH=0 where order_id=@orderid ";
            SQLCommand lsh0 = new SQLCommand(sql, "@orderid", orderid);
            lsh0.ExecuteNonQuery();
            sql = "update LSH_tb set LSH=@lsh where order_id=@orderid and erp_id=@erpid";
            int erpid = 0;
            int lsh = 0;
            try
            {
                for (int i = 0; i < lshparam.Count; i++)
                {
                    foreach (XmlNode item in lshparam[i])
                    {
                        SQLCommand sc = new SQLCommand(sql);                       
                        if (item.Name.Equals("name"))
                            if (item.InnerText != null)
                                erpid = Convert.ToInt32(item.InnerText);
                        if (item.Name.Equals("val"))
                            if (item.InnerText != null)
                                if (IsLshZero(orderid, erpid))
                                {
                                    lsh = Convert.ToInt32(item.InnerText);
                                    sc.Add("@lsh",lsh );
                                    sc.Add("@orderid", orderid);
                                    sc.Add("@erpid", erpid);
                                    cmds.Add(sc);
                                } 
                    }
                    
                    //获取最小流水号 因为要去最小流水号  所以就没有使用xml节点取值的函数 
                    if (i == 0)
                        minLsh = lsh;
                    else //获取最小流水号
                        if (lsh < minLsh)
                        minLsh = lsh;
                }
            }
            catch (Exception e)
            {
                WriteDebug("UpdateLSH", e.Message);
            }
            

            WriteDebug("UpdateLSH", "LSH插入语句："+cmds.Count);
            return cmds;
        }
        /// <summary>
        /// 检验是否有流水号  记录的是最小的流水号
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="erpid"></param>
        /// <returns></returns>
        private bool IsLshZero(int orderid,int erpid)
        {
            string selecLsh = "select LSH from LSH_tb where erp_id=@erpid and order_id=@orderid";
            SQLCommand sc = new SQLCommand(selecLsh);
            sc.Add("@orderid", orderid);
            sc.Add("@erpid", erpid);
            string re = sc.ExecuteScalar();
            if (Convert.ToInt32(re) == 0)
            {
                WriteDebug("IsLshZero", "erpid：" + erpid);
                return true;
            }
            else
                return false;
        }
        /// <summary>
        /// 修改Order表中的物料用量 以及流水号  流水号取最小值
        /// </summary>
        /// <param name="boms"></param>
        /// <param name="orderid"></param>
        /// <returns></returns>
        private List<SQLCommand> UpdateOrder(XmlNodeList boms,int orderid,int minlsh)
        {           
            List<SQLCommand> cmds = new List<SQLCommand>();
            string sql = "update Order_tb set m_dose=@mdose,LSH=@lsh where id=@orderid and mCode=@mcode";
            try
            {
                for (int i = 0; i < boms.Count; i++)
                {
                    SQLCommand sc = new SQLCommand(sql);
                    double mdose = 0;
                    string mcode = "";
                    foreach (XmlNode item in boms[i])
                    {
                        if (item.Name.Equals("val"))
                            if (item.InnerText != null)
                                mdose = Convert.ToDouble(item.InnerText);
                        if (item.Name.Equals("name"))
                            if (item.InnerText != null)
                                mcode = item.InnerText;
                    }
                    sc.Add("@mdose", mdose);
                    sc.Add("@lsh", minlsh);
                    sc.Add("@orderid", orderid);
                    sc.Add("@mcode", mcode);
                    cmds.Add(sc);
                }
            }
            catch (Exception e)
            {
                WriteDebug("UpdateOrder", e.Message);
            }
            
            WriteDebug("UpdateOrder", "插入修改Order_tb语句完成");
            return cmds;
        }
        /// <summary>
        /// 新增床信息
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="pc"></param>
        /// <param name="doc"></param>
        private List<SQLCommand> AddBed(int uid, PCInfo pc, XmlNodeList beds)
        {
            try
            {
                List<SQLCommand> cmds = new List<SQLCommand>();
                string sql = "insert into Bed_tb(id,PLID,order_id,type,name,material_name,material_code,lay_plan,lay_len,cut_len,lay_count,Lsh1,Lsh2,uc,width) values(@bedid,@PLID,@order_id,@type,@name,@material_name,@material_code,@lay_plan,@lay_len,@cut_len,@lay_count,@lsh1,@lsh2,@uc,@width)";
                //流程路径
                string pcPath = GetPCPath(pc.Id) + "\\cut\\";

                for (int i = 0; i < beds.Count; i++)
                {
                    string bedpath = pcPath + beds[i]["name"].InnerText + ".nc";
                    if (!File.Exists(bedpath))
                    {
                        WriteDebug("AddBed", "bedpath:" + bedpath + "不存在");
                        continue;
                    }
                    WriteDebug("AddBed", "bedpath:" + bedpath + "存在");
                    SQLCommand sc = new SQLCommand(sql);
                    int bid = GetNewSafeID(uid);
                    sc.Add("@bedid", bid);
                    sc.Add("@PLID", pc.PLID);
                    sc.Add("@order_id", pc.Id);
                    foreach (XmlNode node in beds[i])
                        AddBed(node, sc);                   

                    cmds.Add(sc);
                }
                WriteDebug("AddBed", "bed插入语句完成,共" + cmds.Count + "条语句");
                return cmds;
            }
            catch (Exception e)
            {
                WriteDebug("AddBed", "异常:"+ e.Message);
                throw;
            }
           
        }
        private void AddBed(XmlNode node, SQLCommand sc)
        {
            if (node.Name == "type")
            {
                AddInt(sc, "@type", node);
            }
            else if (node.Name == "name")
            {
                AddString(sc, "@name", node);
            }
            else if (node.Name.Equals("typeName"))
            {
                AddString(sc, "@material_name", node);
            }
            else if (node.Name.Equals("code"))
            {
                AddString(sc, "@material_code", node);
            }
            else if (node.Name.Equals("color"))
            {
                AddString(sc, "@lay_plan", node);
            }
            else if (node.Name.Equals("len"))
            {
                AddDouble(sc, "@lay_len", node);
            }
            else if (node.Name.Equals("cutLen"))
            {
                AddDouble(sc, "@cut_len", node);
            }
            else if (node.Name.Equals("layCount"))
            {
                AddDouble(sc, "@lay_count", node);
            }
            else if (node.Name.Equals("lsh1"))
            {
                AddInt(sc, "@lsh1", node);
            }
            else if (node.Name.Equals("lsh2"))
            {
                AddInt(sc, "@lsh2", node);
            }
            else if (node.Name.Equals("uc"))
            {
                AddDouble(sc, "@uc", node);
            }
            else if (node.Name.Equals("width"))
            {
                AddDouble(sc, "@width", node);
            }
        }
    }


}
